import { cloudStorage, upload } from "common/jscloud";
import _message from "components/items/message";
const {lib} = ao2
const message = _message()

function cloudUpload(value){
  return new Promise((resolve, reject)=>{
    let $value = [].concat(value)   // value = [{src, file}, ...]
    let targetValue = []
    let existValue = {}
    let upValue = {}
    $value.forEach((val, ii)=>{
      const src = val.src
      const ff  = val.file
      if (ff) {
        upValue[ii] = val
      } else {
        const tmp = lib.urlTOquery(src)
        const hash = tmp.hash
        let   query = tmp.query
        existValue[ii] = {src: lib.queryTOurl(hash, query)}
      }
    })

    const P = []
    Object.keys(upValue).forEach((kk, ii)=>{
      const vv = upValue[kk]
      const src = vv.src
      const ff  = vv.file
      const tmp = lib.urlTOquery(src)
      let   hash = tmp.hash
      let   query = tmp.query || {}
      P.push(new Promise((rso, rej)=>{
        upload(ff, 'newtest/'+ff.name).then(res=>{
          rso({[kk]: {src: lib.queryTOurl(res.fileID, query)} })
        })
      }))
    })

    Promise.all(P).then(res=>{
      const temp = res.reduce((p, n) => Object.assign(p, n), existValue)
      for (const [kk, vv] of Object.entries(temp)) {
        targetValue[kk] = vv.src
      }
      resolve(targetValue.join(','))
    })
  })
}

// 详情页自定义方法
export const detailButton = [
  {'buttons': {
    visible: false,
    input(row, store){
      let uploadElements = {}
      let media = row.__media;

      return {
        title: ' ',
        id: 'saveButton',
        type: 'button',
        value: '保存',
        onClick: async function(e){
          const db = ao2.CLOUD_COLLECTION  // 获取当前云数据库实例
          if (!db) {
            message.tip({ title: '请从列表页开始', type: 'warn', timer: 2000})
            return
          }

          const formElements = store.ctx.elements
          const storeValues = store.storeHelper.value()  // 取得所有表单值
          let   newRow = { id: row.id }
          for (const [key, value] of Object.entries(storeValues)) {
            const element = formElements[key]
            const attributes = element.asset.attributes
            const elementType = attributes.type
            const ky = key.indexOf('-') > -1 ? key.substring(0, key.indexOf('-')) : key
            newRow[ky] = value
            if (elementType === 'uploader') {
              newRow[ky] = await cloudUpload(value)
            }
          }

          if (db) {
            if (row.id) {
              db.doc.set(row.id, newRow, function(){
                message.tip({ title: '保存成功', type: 'success', timer: 2000})
              })
            } else {
              db.doc.add(newRow, function(){
                message.tip({ title: '新增成功', type: 'success', timer: 2000})
              })
            }
          }

        },
        // onClickx(e){
        //   const db = ao2.CLOUD_COLLECTION  // 获取当前云数据库实例
        //   if (!db) {
        //     message.tip({ title: '请从列表页开始', type: 'warn', timer: 2000})
        //     return
        //   }

        //   // uploadElements = {}
        //   const formElements = store.ctx.elements
        //   let   uploadState = true

        //   let   newRow = { id: row.id }
        //   const storeValues = store.storeHelper.value()  // 取得所有表单值
        //   for (const [key, value] of Object.entries(storeValues)) {
        //     const element = formElements[key]
        //     const attributes = element.asset.attributes
        //     const elementType = attributes.type
        //     const ky = key.indexOf('-') > -1 ? key.substring(0, key.indexOf('-')) : key
        //     if (elementType === 'uploader') {
        //       uploadElements[ky] = {
        //         value: (uploadElements[ky] && uploadElements[ky].value)||media[ky]||value||'',
        //         element: element,
        //         required: (attributes.required || false)
        //       }
        //     }
        //     newRow[ky] = value
        //   }

        //   Object.keys(uploadElements).forEach(ky=>{
        //     const $value = uploadElements[ky].value
        //     const required = uploadElements[ky].required
        //     if (!$value && required) {
        //       uploadState = false
        //       const requiredElement = store.getById(ky)
        //       requiredElement.error('还没有上传文件')
        //     } else {
        //       newRow[ky] = $value||''
        //     }
        //   })

        //   if (db && uploadState) {
        //     if (row.id) {
        //       db.doc.set(row.id, newRow, function(){
        //         message.tip({ title: '保存成功', type: 'success', timer: 2000})
        //       })
        //     } else {
        //       db.doc.add(newRow, function(){
        //         message.tip({ title: '新增成功', type: 'success', timer: 2000})
        //       })
        //     }
        //   }
        // }
      }
    }
  }}
]

export const detailButtonForManager = [
  {'buttons': {
    visible: false,
    input(row, store){
      return {
        title: ' ',
        id: 'saveButton',
        type: 'button',
        value: '保存集合',
        onClick(e){
          const db = ao2.CLOUD_COLLECTION  // 获取当前云数据库实例
          if (!db) {
            message.tip({ title: '请从列表页开始', type: 'warn', timer: 2000})
            return
          }

          let   newRow = { id: row.id }
          const storeValues = store.storeHelper.value()  // 取得所有表单值
          for (const [key, value] of Object.entries(storeValues)) {
            const ky = key.substring(0, key.indexOf('-'))
            newRow[ky] = value
          }

          if (db) {
            if (row.id) {
              db.doc.set(row.id, newRow, function(){
                message.tip({ title: '保存成功', type: 'success', timer: 2000})
              })
            } else {
              if (newRow.tableName) {
                if (!newRow.title) {
                  newRow.title = newRow.tableName
                }
                cloudStorage(newRow.tableName)
                setTimeout(() => {
                  db.doc.add(newRow, function(){
                    message.tip({ title: '保存成功', type: 'success', timer: 2000})
                  })
                }, 300);
              }
            }
          }
        }
      }
    }
  }}
]


export const oprateButtons = {
  test: detailButton,
  default: detailButton,
  "CLOUD-TABLE-MANAGER": detailButtonForManager
}


/**
 * bootstrap table的culumn配置
 * 基础配置，并不只作为bootstrap table的配置，同时它还是云开发集合数据表，编辑表单，编辑页，提交信息的配置
 */

export const fildsString = `[
  {'id': {
    title: 'id',
    visible: false,
    valign: 'middle'
  }}, 
  {'title': {
    title: '标题',
    valign: 'middle',
    sortable: true,
    editable: true,
    input: {
      type: 'text',
    }
  }}, 
  {'Desc': {
    title: '操作',
    align: 'right',
    valign: 'middle',
    width: 140,
    events: 'default',
    formatter: [
      '<a class="ss-link-primary ss-block edit" href="javascript:void(0)" title="Edit">修改</a>',
      '<a class="ss-link-primary ss-block remove ml-small" href="javascript:void(0)" title="Remove">删除</a>'
    ]
  }}
]`
export const filds = [
  {'state': {
    checkbox: true,
    align: 'center',
    width: 50,
    valign: 'middle',
  }}, 
  {'id': {
    title: 'id',
    visible: false,
    valign: 'middle'
  }}, 
  {'title': {
    title: '标题',
    valign: 'middle',
    sortable: true,
    editable: true,
    input: {
      type: 'text',
    }
  }}, 
  {'price': {
    title: '价钱',
    valign: 'middle',
    input: {
      type: 'text'
    }
  }}, 
  {'shuoming': {
    title: '说明',
    valign: 'middle',
    input: {
      type: 'text'
    }
  }}, 
  {'Desc': {
    title: '操作',
    align: 'right',
    valign: 'middle',
    width: 140,
    events: 'default',
    formatter: [
      '<a class="ss-link-primary ss-block edit" href="javascript:void(0)" title="Edit">修改</a>',
      '<a class="ss-link-primary ss-block remove ml-small" href="javascript:void(0)" title="Remove">删除</a>'
    ]
  }}
]

export default {
  'test': filds,
  // 云端数据库所有集合的集合表，table构成字段
  'CLOUD-TABLE-MANAGER': [
    {'state': {
      checkbox: true,
      align: 'center',
      width: 50,
      valign: 'middle',
    }}, 
    {'id': {
      title: 'id',
      visible: false,
      valign: 'middle'
    }}, 
    {'tableName': {
      title: '集合英文名',
      valign: 'middle',
      input: {
        type: 'text'
      }
    }}, 
    {'title': {
      title: '集合名称',
      valign: 'middle',
      sortable: true,
      editable: true,
      input: {
        type: 'text',
      }
    }}, 
    {'filds': {
      title: '字段配置',
      visible: false,
      valign: 'middle',
      input: {
        type: 'textarea',
        itemClass: 'entity-flex'
      },
    }}, 
    {'Desc': {
      title: '操作',
      align: 'right',
      valign: 'middle',
      width: 140,
      events: 'CLOUD-TABLE-MANAGER',
      formatter: [  // bootstrap table原生需要指定该属性为function，这里做了一次适配，在生成bt的表格前自动将此数据转换成function
        '<a class="ss-link-primary ss-block edit" href="javascript:void(0)" title="Edit">修改</a>',
        '<a class="ss-link-primary ss-block remove ml-small" href="javascript:void(0)" title="Remove">删除</a>'
      ]
    }}
  ]
}